import { msConfig as nodeApi } from 'cn.keytop.stc.webide.demo-client';
import { msConfig as nodeApi2 } from 'cn.keytop.stc.webide.demo2-client';

import request from '../plugins/request';
import _merge from 'lodash/merge';
import { TOKEN } from '@/utils/storageKey';

type ContentType =
  | 'application/x-www-form-urlencoded'
  | 'multipart/form-data'
  | 'application/json'
  | 'text/plain';

function common(branch: string, config?: IAxiosRequestConfig) {
  return {
    request(
      method: any,
      contentType: ContentType,
      headers: object,
      parameters: any,
      ext?: any
    ): Promise<any> {
      let nodeAPIConfig = {};
      /**
       * 从参数中提取 nodeAPIConfig 配置当前接口全局相关。
       * 接口包目前已经更新，新增 ext 在方法参数尾部，所以暂时不用这种比较不友好的方式，
       * 当时目前还是做了兼容处理
       */
      if (parameters.nodeAPIConfig) {
        nodeAPIConfig = parameters.nodeAPIConfig;
        Reflect.deleteProperty(parameters, 'nodeAPIConfig');
      } else if (ext) {
        nodeAPIConfig = ext;
      }

      method = method.toLowerCase();
      // 判断当前是上传文件相关接口
      method = contentType === 'multipart/form-data' ? 'upload' : method;

      // @ts-ignore
      return request[method](
        '',
        parameters,
        _merge(
          {
            headers: Object.assign({ 'Content-Type': contentType }, headers)
          },
          // 分支级
          config,
          // 接口级
          nodeAPIConfig,
          // 标志当前是 node api 进行请求
          { branch }
        )
      );
    }
  };
}

nodeApi.use(common('node'));
nodeApi2.use(
  common('node', { headers: { 'node-token': localStorage.getItem(TOKEN) } })
);
